import { useState, useEffect } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";

import "@wangeditor/editor/dist/css/style.css"; // 引入 css

interface IProps {
  customUpload?: (file: File, insertFn: (url: string) => void) => void;
  onChange?: (html: string) => void;
  value?: string;
}

function RichEditor({ value, onChange, ...props }: IProps) {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法

  // console.log("", value);

  const customUpload = () => {
    return {
      customUpload: (file, insertFn) => {
        props?.customUpload?.(file, (url) => {
          insertFn(url, "", url);
        });
      },
    };
  };

  // const onChange = (html: string) => {
  //   props.onChange?.(html);
  // };
  const handlOnChange = (editor: IDomEditor) => {
    const html = editor.getHtml();
    if(value === undefined && html === "<p><br></p>") return;
    console.log("html", value, html);
    onChange?.(html);
  };

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: "请输入内容...",
    MENU_CONF: {
      uploadImage: customUpload(),
      uploadVideo: customUpload(),
    },
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // if (value === undefined) return null;

  return (
    <>
      <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={value}
          onCreated={setEditor}
          // onChange={(editor) => onChange?.(editor.getHtml())}
          onChange={handlOnChange}
          mode="default"
          style={{ height: "500px", overflowY: "hidden" }}
        />
      </div>
    </>
  );
}

export default RichEditor;
